package com.yzc.filter;

import com.yzc.util.JwtUtil;
import io.jsonwebtoken.JwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtUtil jwtUtil;
    private final RedisTemplate<String, String> redisTemplate;

    public JwtAuthenticationFilter(JwtUtil jwtUtil, RedisTemplate<String, String> redisTemplate) {
        this.jwtUtil = jwtUtil;
        this.redisTemplate = redisTemplate;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain)
            throws ServletException, IOException {

        String authHeader = request.getHeader("Authorization");

        String token = jwtUtil.resolveToken(authHeader);   //从请求头（如 Authorization: Bearer <token>）或 Cookie 中提取 JWT。
        log.error("token====================={}", token);
        if (token == null) {                                            // 如果未找到 token，直接放行请求，交给后续过滤器或控制器处理。此时用户被视为“未认证”。
            filterChain.doFilter(request, response);
            return;
        }
        try {                                                           //
            if (jwtUtil.validateToken(token)) {
                Long userId = jwtUtil.extractUserId(token);             //提取用户ID
                String redisKey = String.format("user:token:%s", userId);   // 构造 Redis 键
                if (Boolean.FALSE.equals(redisTemplate.hasKey(redisKey))) { // 检查 Redis 中是否存在该用户的 token
                    throw new JwtException("Token 已失效");
                }

                String username = jwtUtil.extractUsername(token);       // 提取用户名
                List<GrantedAuthority> authorities = Collections.emptyList();

                UsernamePasswordAuthenticationToken authentication =
                        new UsernamePasswordAuthenticationToken(username, null, authorities);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        } catch (JwtException e) {
            SecurityContextHolder.clearContext();
            throw new ServletException("JWT验证失败", e);  // 包装异常
        }

        filterChain.doFilter(request, response);
    }
}